package com.yupi.springbootinit.job.once;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yupi.springbootinit.model.entity.Post;
import com.yupi.springbootinit.service.PostService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.Assertions;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

// 取消注释 @Component 后, 每次启动springboot项目时会执行一次run方法
@Component
@Slf4j
public class FetchInitPostList implements CommandLineRunner {
    @Resource
    private PostService postService;

    @Override
    public void run(String... args) throws Exception {
        List<Post> postList = new ArrayList<>();

        for (int i = 1; i < 5; i++) {
            // TODO 1.数据爬取
            String json = "{\n" +
                    "    \"current\": " + i + ",\n" +
                    "    \"pageSize\": 8,\n" +
                    "    \"sortField\": \"createTime\",\n" +
                    "    \"sortOrder\": \"descend\",\n" +
                    "    \"category\": \"文章\",\n" +
                    "    \"reviewStatus\": 1\n" +
                    "}";
            String result = HttpRequest.post("https://www.code-nav.cn/api/post/search/page/vo")
                    .body(json)
                    .execute()
                    .body();
            System.out.println(result);

            // TODO 2.json转对象
            Map<String, Object> map = JSONUtil.toBean(result, Map.class);
            JSONObject data = (JSONObject) map.get("data");
            JSONArray records = (JSONArray) data.get("records");


            for (Object record : records) {
                JSONObject tempRecord = (JSONObject) record;

                Post post = new Post();
                post.setTitle(tempRecord.getStr("title"));
                post.setContent(tempRecord.getStr("content"));
                JSONArray tags = (JSONArray) tempRecord.get("tags");
                List<String> tagList = tags.toList(String.class);
                post.setTags(JSONUtil.toJsonStr(tagList));
                post.setUserId(1L);

                postList.add(post);
            }
            // System.out.println(postList);
        }

        // TODO 3.数据入库
        boolean b = postService.saveBatch(postList);
        if(b){
            log.info("FetchInitPostList 初始化帖子列表成功, 条数={}", postList.size());
        }else{
            log.error("获取初始化帖子列表失败");
        }
    }
}
